﻿Imports Aspose.Words
Imports System.Net
Imports System.IO
Imports System.IO.Path
Imports System.Data
Imports VSModel
Imports Cls_Common

Partial Class Control_PrintLabel_Create
    Inherits System.Web.UI.UserControl

    Protected Sub btnSave_Click(sender As Object, e As System.EventArgs) Handles btnSave.Click
        Using data As New VSEntities
            Dim p = (From q In data.WareHouses Where q.BatchNo = txtBatchno.Text.Trim Select q).FirstOrDefault
            If p Is Nothing Then
                Excute_Javascript("Alertbox('Không tồn tại dữ liệu có Batch No này, Vui lòng kiểm tra lại.');", Me.Page, True)
            Else
                'Excute_Javascript("Alertbox('Có data ');", Me.Page, True)
                'update ngay sx ngay het han
                If txtNgaySanXuat.Text <> "" Then
                    p.ManufacturedDate = StringToDate(txtNgaySanXuat.Text)
                Else
                    p.ManufacturedDate = Nothing
                End If
                If txtHanSuDung.Text <> "" Then
                    p.ExpiredDate = StringToDate(txtHanSuDung.Text)
                Else
                    p.ExpiredDate = Nothing
                End If
                data.SaveChanges()

                Try
                    Dim applicationPath As String = Server.MapPath(Request.ApplicationPath)
                    If Not applicationPath.EndsWith("\") Then
                        applicationPath = applicationPath + "\"
                    End If
                    Dim licenseFile As String = Path.Combine(applicationPath, "bin\Aspose.Words.lic")
                    If (File.Exists(licenseFile)) Then
                        Dim license As Aspose.Words.License = New Aspose.Words.License()
                        license.SetLicense(licenseFile)

                        Dim strDocFile As String = getDocFile()
                        Dim doc As Aspose.Words.Document = New Aspose.Words.Document(strDocFile)

                        Dim strDirTemp As String = applicationPath & "viewerTemp"
                        If Not Directory.Exists(strDirTemp) Then
                            Directory.CreateDirectory(strDirTemp)
                        End If
                        If Not strDirTemp.EndsWith("\") Then
                            strDirTemp = strDirTemp + "\"
                        End If

                        Dim swfFile As String = GetFileNameWithoutExtension(strDocFile) & ".swf"
                        Dim pngTemp As String = strDirTemp & swfFile
                        doc.Save(pngTemp, Aspose.Words.SaveFormat.Swf)

                        If File.Exists(pngTemp) Then
                            Call writeSwf("../../viewerTemp/" & swfFile)
                        End If
                        If Not IsNothing(doc) Then
                            doc = Nothing
                        End If
                    End If
                Catch ex As Exception

                End Try
            End If

        End Using
    End Sub



    Function getDocFile() As String
        Dim strResult As String = ""
        Try
            Dim applicationPath As String = Server.MapPath(Request.ApplicationPath)
            If Not applicationPath.EndsWith("\") Then
                applicationPath = applicationPath + "\"
            End If
            Dim licenseFile As String = Path.Combine(applicationPath, "bin\Aspose.Words.lic")
            If (File.Exists(licenseFile)) Then
                Dim license As Aspose.Words.License = New Aspose.Words.License()
                license.SetLicense(licenseFile)

                Dim strDocFile As String = applicationPath & "Template\labelTemplate.doc"
                Dim doc As Aspose.Words.Document = New Aspose.Words.Document(strDocFile)

                Dim builder As DocumentBuilder = New DocumentBuilder(doc)
                Using data As New VSEntities
                    'lay hinh do canh bao
                    Dim iLst As IList = (From q In data.uspLabelGetHinhDo(txtBatchno.Text, 1) Select q).ToList

                    Dim _iLstCanhBao As IList = (From q In data.uspLabelGetHinhDo(txtBatchno.Text, -1) Select q Order By q.CanhBaoNguyCo).ToList

                    Dim intSeq As Integer = 1
                    Dim FileURL As String = ""
                    Dim strTuCanhBao As String = ""
                    Dim _CanhBaoNguyCo As String = ""
                    Dim fieldName1 As String = "iconWarning1"
                    Dim fieldName2 As String = "iconWarning2"
                    Dim fieldName3 As String = "iconWarning3"
                    Dim fieldName4 As String = "iconWarning4"
                    Dim fieldName5 As String = "iconWarning5"
                    Dim arrFileURL As String = "" 'dung de luu ca'c file URL va bo trung lap

                    Dim intSeqCanhBao As Integer = 1
                    If Not _iLstCanhBao Is Nothing AndAlso iLst.Count > 0 Then
                        Dim strTemp As String = ""
                        For Each proc In _iLstCanhBao
                            _CanhBaoNguyCo = proc.CanhBaoNguyCo.ToString
                            If _CanhBaoNguyCo <> strTemp Then
                                Select Case intSeqCanhBao
                                    Case 1
                                        InsertCanhBaoNguyCo(builder, "CanhBaoNguyCo1", _CanhBaoNguyCo.Trim)
                                    Case 2
                                        InsertCanhBaoNguyCo(builder, "CanhBaoNguyCo2", _CanhBaoNguyCo.Trim)
                                    Case 3
                                        InsertCanhBaoNguyCo(builder, "CanhBaoNguyCo3", _CanhBaoNguyCo.Trim)
                                    Case 4
                                        InsertCanhBaoNguyCo(builder, "CanhBaoNguyCo4", _CanhBaoNguyCo.Trim)
                                    Case 5
                                        InsertCanhBaoNguyCo(builder, "CanhBaoNguyCo5", _CanhBaoNguyCo.Trim)
                                End Select
                                intSeqCanhBao += 1
                            End If
                            strTemp = _CanhBaoNguyCo

                        Next
                    End If

                    If Not iLst Is Nothing AndAlso iLst.Count > 0 Then
                        For Each proc In iLst
                            FileURL = ""
                            If Not IsNothing(proc.FileURL) Then
                                FileURL = proc.FileURL.ToString
                                _CanhBaoNguyCo = proc.CanhBaoNguyCo.ToString
                                strTuCanhBao = strTuCanhBao & "@" & proc.TuCanhBao.ToString
                                arrFileURL = arrFileURL + "@" + FileURL
                            End If
                            'Select Case intSeq
                            '    Case 1
                            '        ' InsertImageFromURL(builder, FileURL, 85, 85, fieldName1)
                            '        InsertCanhBaoNguyCo(builder, "CanhBaoNguyCo1", _CanhBaoNguyCo.Trim)
                            '    Case 2
                            '        'InsertImageFromURL(builder, FileURL, 85, 85, fieldName2)
                            '        InsertCanhBaoNguyCo(builder, "CanhBaoNguyCo2", _CanhBaoNguyCo.Trim)
                            '    Case 3
                            '        ' InsertImageFromURL(builder, FileURL, 85, 85, fieldName3)
                            '        InsertCanhBaoNguyCo(builder, "CanhBaoNguyCo3", _CanhBaoNguyCo.Trim)
                            '    Case 4
                            '        ' InsertImageFromURL(builder, FileURL, 85, 85, fieldName4)
                            '        InsertCanhBaoNguyCo(builder, "CanhBaoNguyCo4", _CanhBaoNguyCo.Trim)
                            '    Case 5
                            '        ' InsertImageFromURL(builder, FileURL, 85, 85, fieldName5)
                            '        InsertCanhBaoNguyCo(builder, "CanhBaoNguyCo5", _CanhBaoNguyCo.Trim)
                            'End Select
                            'intSeq += 1
                        Next

                        ' xu ly file Hinh do bi dublicate
                        Dim arrFileURLResult = removeDublicate(arrFileURL)
                        intSeq = 1
                        For Each _fileURL In arrFileURLResult
                            Select Case intSeq
                                Case 1
                                    InsertImageFromURL(builder, _fileURL, 85, 85, fieldName1)
                                Case 2
                                    InsertImageFromURL(builder, _fileURL, 85, 85, fieldName2)
                                Case 3
                                    InsertImageFromURL(builder, _fileURL, 85, 85, fieldName3)
                                Case 4
                                    InsertImageFromURL(builder, _fileURL, 85, 85, fieldName4)
                                Case 5
                                    InsertImageFromURL(builder, _fileURL, 85, 85, fieldName5)
                            End Select
                            intSeq = intSeq + 1
                        Next
                        'end xu ly file hinh do bi dublicate

                        FileURL = "http://" & HttpContext.Current.Request.ServerVariables("HTTP_HOST") & ConfigurationManager.AppSettings("ApplicationName") & "/Images/warnBlank.png"
                        For i As Integer = arrFileURLResult.Length + 1 To 5
                            Select Case i
                                Case 1
                                    InsertImageFromURL(builder, FileURL, 85, 85, fieldName1)
                                    InsertCanhBaoNguyCo(builder, "CanhBaoNguyCo1", "")
                                Case 2
                                    InsertImageFromURL(builder, FileURL, 85, 85, fieldName2)
                                    InsertCanhBaoNguyCo(builder, "CanhBaoNguyCo2", "")
                                Case 3
                                    InsertImageFromURL(builder, FileURL, 85, 85, fieldName3)
                                    InsertCanhBaoNguyCo(builder, "CanhBaoNguyCo3", "")
                                Case 4
                                    InsertImageFromURL(builder, FileURL, 85, 85, fieldName4)
                                    InsertCanhBaoNguyCo(builder, "CanhBaoNguyCo4", "")
                                Case 5
                                    InsertImageFromURL(builder, FileURL, 85, 85, fieldName5)
                                    InsertCanhBaoNguyCo(builder, "CanhBaoNguyCo5", "")
                            End Select
                        Next
                    Else
                        FileURL = "http://" & HttpContext.Current.Request.ServerVariables("HTTP_HOST") & ConfigurationManager.AppSettings("ApplicationName") & "/Images/warnBlank.png"
                        InsertImageFromURL(builder, FileURL, 85, 85, fieldName1)
                        InsertCanhBaoNguyCo(builder, "CanhBaoNguyCo1", "Không có")
                        InsertImageFromURL(builder, FileURL, 85, 85, fieldName2)
                        InsertCanhBaoNguyCo(builder, "CanhBaoNguyCo2", "")
                        InsertImageFromURL(builder, FileURL, 85, 85, fieldName3)
                        InsertCanhBaoNguyCo(builder, "CanhBaoNguyCo3", "")
                        InsertImageFromURL(builder, FileURL, 85, 85, fieldName4)
                        InsertCanhBaoNguyCo(builder, "CanhBaoNguyCo4", "")
                        InsertImageFromURL(builder, FileURL, 85, 85, fieldName5)
                        InsertCanhBaoNguyCo(builder, "CanhBaoNguyCo5", "")
                    End If

                    'add tu canh bao
                    builder.MoveToMergeField("TuCanhBao")
                    builder.Bold = True
                    builder.Font.Name = "Arial"
                    builder.Font.Size = "8"
                    strTuCanhBao = strTuCanhBao.ToUpper
                    strTuCanhBao = getWarning(strTuCanhBao)
                    builder.Write(strTuCanhBao)
                End Using

                'xu ly thanh phan supscript


                Dim clstp As New clsDALabelPrint
                Dim dttp As DataTable = clstp.SelectLabelPrint(txtBatchno.Text)
                clstp.Destructor()
                clstp = Nothing
                If dttp.Rows.Count > 0 Then
                    InsertThanhPhan(builder, "ThanhPhan_1", dttp.Rows(0)("ThanhPhan_1"))
                    InsertThanhPhan(builder, "ThanhPhan_2", dttp.Rows(0)("ThanhPhan_2"))
                    InsertThanhPhan(builder, "ThanhPhan_3", dttp.Rows(0)("ThanhPhan_3"))
                    InsertThanhPhan(builder, "ThanhPhan_4", dttp.Rows(0)("ThanhPhan_4"))
                    InsertThanhPhan(builder, "ThanhPhan_5", dttp.Rows(0)("ThanhPhan_5"))
                Else
                    InsertThanhPhan(builder, "ThanhPhan_1", "")
                    InsertThanhPhan(builder, "ThanhPhan_2", "")
                    InsertThanhPhan(builder, "ThanhPhan_3", "")
                    InsertThanhPhan(builder, "ThanhPhan_4", "")
                    InsertThanhPhan(builder, "ThanhPhan_5", "")
                End If


                Dim cls As New clsDALabelPrint
                Dim dt As DataTable = cls.SelectLabelPrint(txtBatchno.Text)
                cls.Destructor()
                cls = Nothing
                If dt.Rows.Count > 0 Then
                    doc.MailMerge.Execute(dt)
                    strResult = applicationPath & "viewerTemp"
                    If Not Directory.Exists(strResult) Then
                        Directory.CreateDirectory(strResult)
                    End If
                    If Not strResult.EndsWith("\") Then
                        strResult = strResult + "\"
                    End If
                    strResult &= Format(Now, "yyyyMMddhhmmssfff") & ".doc"
                    doc.Save(strResult, Aspose.Words.SaveFormat.Doc)
                    If Not IsNothing(doc) Then
                        doc = Nothing
                    End If
                End If
            End If
        Catch ex As Exception
            Excute_Javascript("Alertbox('Xuất hiện lỗi:" & ex.Message.ToString & "');", Me.Page, True)
        End Try
        Return strResult
    End Function

    Function getWarning(ByVal str As String) As String
        Dim lstArr = str.Split("@")
        If lstArr.Contains("NGUY HIỂM") Then
            Return "NGUY HIỂM"
        ElseIf lstArr.Contains("CẢNH BÁO") Then
            Return "CẢNH BÁO"
        Else
            Return "KHÔNG CÓ"
        End If

    End Function
    'remove dublicate item in Array
    Function removeDublicate(ByVal arr As String) As String()
        Dim lstArr = arr.Split("@")
        Dim lstResult() As String = {}
        Dim i = 0
        For Each a In lstArr
            'neu mang da add ko chua phan tu cua a
            If Not lstResult.Contains(a) AndAlso a <> "" Then
                ReDim Preserve lstResult(i)
                lstResult(i) = a
                i = i + 1
            End If
        Next
        Return lstResult
    End Function


    Private Sub writeSwf(ByVal _swf As String)
        Try
            Dim _xmlFile As String = ""
            Dim _strInfo As String = ""
            If _swf.ToLower.EndsWith(".swf") Then
                _strInfo &= " writeSwf('" & _swf & "');" & vbCrLf
            End If
            Excute_Javascript(_strInfo, Me.Page, True)
        Catch ex As Exception
        End Try
    End Sub

    Private Sub InsertImageFromURL(ByVal builder As DocumentBuilder, ByVal url As String, ByVal width As Double, ByVal height As Double, ByVal fieldName As String)
        Try
            'Prepare the web page we will be asking for
            Dim request As HttpWebRequest = DirectCast(WebRequest.Create(url), HttpWebRequest)
            request.Method = "GET"
            request.ContentType = "image/JPEG"
            request.UserAgent = "Mozilla/4.0+(compatible;+MSIE+5.01;+Windows+NT+5.0"
            'Execute the request
            Dim response As HttpWebResponse = DirectCast(request.GetResponse(), HttpWebResponse)
            'We will read data via the response stream
            Dim resStream As Stream = response.GetResponseStream()
            'Write content into the MemoryStream
            Dim resReader As New BinaryReader(resStream)
            Dim imgStream As New MemoryStream(resReader.ReadBytes(CInt(response.ContentLength)))

            'Insert image into the document
            builder.MoveToMergeField(fieldName)
            builder.InsertImage(imgStream, width, height)
            'Handle web exceptions
        Catch
        End Try

    End Sub
    Private Sub InsertCanhBaoNguyCo(ByVal builder As DocumentBuilder, ByVal fieldName As String, ByVal _str As String)
        'Insert text to file
        builder.MoveToMergeField(fieldName)
        builder.Font.Size = "8"
        builder.Write(RemoveHtmlTags(_str).Trim())

    End Sub
    Private Sub InsertThanhPhan(ByVal builder As DocumentBuilder, ByVal fieldName As String, ByVal _str As String)
        'Insert html to file
        builder.MoveToMergeField(fieldName)
        builder.InsertHtml("<span style='font-size:7pt; font-family:Arial'>" & _str.Trim & "</span>")
    End Sub
    Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
            'xu ly jquery khi post back
            Dim script As ScriptManager = ScriptManager.GetCurrent(Me.Page)
            If Not script Is Nothing AndAlso script.IsInAsyncPostBack Then
                ScriptManager.RegisterStartupScript(Me.Page, Me.Page.GetType, "jqueryEnable", "ajaxJqueryMSDS()", True)
            Else
                Me.Page.ClientScript.RegisterStartupScript(Me.Page.GetType(), "jqueryEnable", String.Concat("Sys.Application.add_load(function(){", "ajaxJqueryMSDS()", "});"), True)
            End If
        End If
    End Sub

    Protected Sub btnReset_Click(sender As Object, e As System.EventArgs) Handles btnReset.Click
        Response.Redirect(MainDomain & "Page/PrintLabel/Create.aspx")
    End Sub
    Protected Sub btnExportWord_Click(sender As Object, e As System.EventArgs) Handles btnExportWord.Click

        Dim strFileName = getDocFile()
        Dim bareFile = strFileName.Replace(Server.MapPath("~/viewerTemp/"), "")
        Excute_Javascript("open_iframe('" + MainDomain & "Page/PrintLabel/ExportFile.aspx?f=" + bareFile + "','NhanHoaChat')", Me.Page)

    End Sub


    Protected Sub btnExportPdf_Click(sender As Object, e As System.EventArgs) Handles btnExportPdf.Click

        Dim strDocFile = getDocFile()
        'save PDF
        Dim strPdfFile As String = strDocFile.Replace(".doc", ".pdf")
        If Not File.Exists(strPdfFile) Then
            Dim licenseFile As String = Server.MapPath("~") & "\bin\Aspose.Words.lic"
            If (File.Exists(licenseFile)) Then
                Dim license As Aspose.Words.License = New Aspose.Words.License()
                license.SetLicense(licenseFile)
                Dim doc As Aspose.Words.Document = New Aspose.Words.Document(strDocFile)
                doc.Save(strPdfFile, SaveFormat.Pdf)
                If Not IsNothing(doc) Then
                    doc = Nothing
                End If
            End If
        End If

        Dim bareFile = strPdfFile.Replace(Server.MapPath("~/viewerTemp/"), "")
        Excute_Javascript("open_iframe('" + MainDomain & "Page/PrintLabel/ExportFile.aspx?f=" + bareFile + "','NhanHoaChat')", Me.Page)

    End Sub

End Class



